class Company < ActiveRecord::Base
  belongs_to :created_by, :class_name => "User", :foreign_key => "user_id"
  has_many :users
  
  def self.create(name, password, twitter_user_id)
    user = User.includes(:company).find_by_twitter_user_id(twitter_user_id)
    company = Company.find_by_name(name)

    if user.company.nil? && company.nil?
      Company.transaction do
        company = Company.new
        company.name = name
        company.password = password
        company.created_by = user
        company.save!

        user.company = company
        user.save!
      end
    end
  end
  
  def self.add_user(name, password, twitter_user_id)
    company = Company.authenticate(name, password)
    user = User.includes(:company).find_by_twitter_user_id(twitter_user_id)

    unless company.nil? || !user.company.nil?
      user.company = company
      user.save
    end
  end

  def self.random_string(len)
    #generate a random password consisting of strings and digits
    chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    new_password = ""
    1.upto(len) { |i| new_password << chars[rand(chars.size-1)] }
    return new_password
  end

  def self.encrypt(pass, salt)
     Digest::SHA1.hexdigest(pass+salt)
   end

  def password=(pass)
    @password = pass
    self.salt = Company.random_string(10) if !self.salt?
    self.hashed_password = Company.encrypt(@password, self.salt)
  end

  def self.authenticate(name, pass)
    company = Company.find_by_name(name)
    return nil if company.nil?
    return company if Company.encrypt(pass, company.salt) == company.hashed_password
    nil
  end

end
